import { blobToBase64, sendPost, uploadFile } from "./http";
import { uploadOSS } from "./oss";
import api from "../config/api";
import Recorder from "js-audio-recorder";
const recorder = new Recorder({
  sampleBits: 8, // 采样位数，支持 8 或 16，默认是16
  sampleRate: 24000, // 采样率，支持 11025、16000、22050、24000、44100、48000，根据浏览器默认值，我的chrome是48000
  numChannels: 1 // 声道，支持 1 或 2， 默认是1
  // compiling: false,(0.x版本中生效,1.x增加中)  // 是否边录边转换，默认是false
});

export default {
  watch: {
    $route() {
      this.id = this.$route.query.id;
    },
    id(e) {
      console.log(e);
      location.reload();
    }
  },
  methods: {
    getData(id) {
      var that = this;
      sendPost(api.getSubjectDetails, {
        id: id
      }).then(res => {
        // console.log(res)
        that.subject = res.data;
        that.eSubjectType = res.data.eSubjectType;

        // that.countDown= res.data.readyTime
        // that.recordingCountDown=res.data.answerTime
        if (res.data.practiceList) {
          that.practiceList = res.data.practiceList;
        }
        that.last = res.data.last;
        that.next = res.data.next;
        // console.log("labelStyle",res.data.labelStyle)
        // if (that.surplusTime > 0) {
        //   setInterval(that.countDownTime, 1000)
        // }
      });
    },
    /**
     * 将秒转换为 分:秒
     * s int 秒数
     */
    s_to_hs(s) {
      //计算分钟
      //算法：将秒数除以60，然后下舍入，既得到分钟数
      var h;
      h = Math.floor(s / 60);
      //计算秒
      //算法：取得秒%60的余数，既得到秒数
      s = s % 60;
      //将变量转换为字符串
      h += "";
      s += "";
      //如果只有一位数，前面增加一个0
      h = h.length == 1 ? "0" + h : h;
      s = s.length == 1 ? "0" + s : s;
      return h + ":" + s;
    },
    //答题时间倒计时
    countDownTime() {
      if (this.surplusTime > 0) {
        // 时间戳来写
        this.surplusTime--;
      }
    },

    // 作业本里面录音题的获取与上传
    getFile() {
      let file = new window.File([recorder.getWAVBlob()], "yinp.wav", {
        type: "wav"
      });

      console.log(file.size<100000);
      if (file.zize < 100000) {
        this.$msg.info('录音时间过短！')
        return
      } else {
        console.log(1122);
        uploadOSS(file, "records").then(res => {
          console.log(res);
          sendPost(api.submitWorkDetail, {
            id: this.id1,
            answer: res,
            times: this.answerTime
          }).then(res => {
            if (res.msg == "提交成功") {
              this.$msg.success("申请批改成功!");
              this.answer = "";

              // 更新修改的按钮样式
              var that = this;
              this.isSub = true;
              // 再次刷新数据，更新视图
              this.$emit("updateList");
            }
          });
        });

      }

    },
    //提交作业
    addPractice() {
      let toltime = recorder.duration; //录音总时长
      let fileSize = recorder.fileSize; //录音总大小
      this.totalTime = parseInt(toltime);
      if (this.totalTime < 1) {
        this.$msg.info("请录音后再提交");
        return;
      }
      // if (this.surplusTime <= 0) {
      //   this.$msg.error("超过答题时间,请刷新页面重新作答！");
      //   return;
      // }
      var that = this;
      if (this.url == "") {
        that.$msg.error("请先答题！");
        return;
      }
      let file = new window.File([recorder.getWAVBlob()], "yinp.wav", {
        type: "wav"
      });

      console.log(file);

      uploadOSS(file, "records").then(res => {
        sendPost(api.submitAnswer, {
          id: that.$route.query.id,
          answer: res,
          times: that.answerTime
        }).then(r => {
          that.$msg({
            message: "答案提交成功",
            type: "success"
          });
          that.$router.go(0);

          this.getData(that.$route.query.id);
          // this.$router.go(0);
          // 提交作业后，不再倒计时
          that.url = ""; // 隐藏录音播放器
        });
      });
    },
    // 准备倒计时
    countDownHandle() {
      if (this.countDown > 0) {
        this.countDown--;
      } else if (this.countDown == 0) {
        this.countDown = 0;
        // clearInterval(this.interval.mkf)
        // 倒计时结束，自动开始录音
        this.startRecorder();
      }
    },
    // 获取麦克风权限
    getPermission() {
      var that = this;
      return Recorder.getPermission().then(
        () => {
          // this.$msg.success("获取麦克风权限成功");
          // that.interval.mkf=setInterval(this.countDownHandle, 1000,10)
          that.isOpen = true;
          that.tips = true;
        },
        error => {
          that.tips = false;
          this.$msg.error("麦克风未开启");
        }
      );
    },
    // 开始录音
    startRecorder() {
      var that = this;
      recorder.start().then(() => {
        that.readyTime = 0;
        that.$msg.success("开始录音");
      });
    },
    // 获取录音文件
    getRecorder() {
      recorder.stop();
      // this.$msg.success("录制结束");
      var that = this;
      let toltime = recorder.duration; //录音总时长
      let fileSize = recorder.fileSize; //录音总大小
      this.totalTime = parseInt(toltime);
      if (this.totalTime < 1) {
        // this.$msg.info('录音时间不能少于1秒')
        return;
      }

      blobToBase64(recorder.getWAVBlob()).then(res => {
        // 转化后的base64
        // console.log("base64", res);
        that.url = res;

        that.Rurl = res;
      });
      clearInterval(that.interval.mkf);
    },

    // 停止录音
    stopRecorder() {
      recorder.stop();
    },
    // 录音播放
    playRecorder() {
      recorder.play();
      this.type = "pause";
      if (this.percent < this.totalTime) {
      }
    },
    // 暂停录音播放
    pausePlayRecorder() {
      recorder.pausePlay();
      this.type = "play";
    }
  }
};
